package ntu.metaweb.http;

import java.io.IOException;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLDecoder;
import java.util.HashMap;

import ntu.metaweb.Metaweb;
import ntu.metaweb.storage.FiveStarRating;
import ntu.metaweb.storage.WebPageQuery;
import ntu.metaweb.storage.WebPageQueryKey;
import ntu.metaweb.update.PageAverageRating;
import ntu.metaweb.update.UpdatePageRating;
import ntu.p2p.dht.DHTContent;
import ntu.p2p.dht.DHTContentKey;
import ntu.p2p.dht.messaging.DHTUpdateObjectMessage;
import rice.Continuation;

import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;

@SuppressWarnings("restriction")
public class UpdatePageRatingHandler implements CommandHandler {

	@Override
	public void handleCommand(final HttpExchange exchange,
			final HashMap<String, String> params) throws IOException {
		if (params.get("url_parameter").equals("null"))
			params.put("url_parameter", "");
		
		final WebPageQueryKey key = new WebPageQueryKey(
				URLDecoder.decode(params.get("url"), "UTF-8"), 
				URLDecoder.decode(params.get("url_parameter"), "UTF-8"));
		Metaweb.getInstance().getDhtApplication().lookup(key, 
				new Continuation<DHTContent,Exception>() {

					@Override
					public void receiveException(Exception exception) {

					}

					@Override
					public void receiveResult(DHTContent result) {
						// create and insert web page query object
						System.out.println("update page rating");
						for (String a : params.keySet()) {
							System.out.println(a + " " + params.get(a));
						}
						DHTUpdateObjectMessage updateMessage = new DHTUpdateObjectMessage(key, 
								new UpdatePageRating(new FiveStarRating(params.get("username"), 
										Integer.parseInt(params.get("rating")))));
						Metaweb.getInstance().getDhtApplication().update(key, updateMessage, 
								new Continuation<Object, Exception>() {

									@Override
									public void receiveException(Exception exception) {
										// TODO Auto-generated method stub
										
									}

									@Override
									public void receiveResult(Object result) {
										System.out.println("update successs");
										onReceiveResult(exchange, result);
									}
						});
						
						WebPageQuery webpagequery = (WebPageQuery) result;
						webpagequery.addRating(params.get("username"), 
								Integer.parseInt(params.get("rating")));
						double averageRating = webpagequery.getAverageRating();
						PageAverageRating diff = 
							new PageAverageRating(webpagequery.getURL(),	averageRating);
						
						for (URL temp : webpagequery.getInLink().keySet()) {
							DHTContentKey tempkey = new WebPageQueryKey(temp);
							Metaweb.getInstance().getDhtApplication().update(
									tempkey, new DHTUpdateObjectMessage(tempkey, diff), 
									new Continuation<Object, Exception>() {

										@Override
										public void receiveException(Exception exception) {
											// TODO Auto-generated method stub
											
										}

										@Override
										public void receiveResult(Object result) {
											// TODO Auto-generated method stub
											
										}
									});		
						}
						
						for (URL temp : webpagequery.getOutLink().keySet()) {
							DHTContentKey tempkey = new WebPageQueryKey(temp);
							Metaweb.getInstance().getDhtApplication().update(
									tempkey, new DHTUpdateObjectMessage(tempkey, diff), 
									new Continuation<Object, Exception>() {

										@Override
										public void receiveException(Exception exception) {
											// TODO Auto-generated method stub
											
										}

										@Override
										public void receiveResult(Object result) {
											// TODO Auto-generated method stub
											
										}
									});		
						}

					}
		});
	}

	@SuppressWarnings("restriction")
	protected void onReceiveResult(HttpExchange exchange, Object result) {
		try {
			System.out.println("sending update success...");
			Headers responseHeaders = exchange.getResponseHeaders();
			responseHeaders.set("Content-Type", "text/xml");

			exchange.sendResponseHeaders(200, 0);

			OutputStream responseBody = exchange.getResponseBody();
			String temp = "<xmlresponse>\n" 
					+ "<returncode>1</returncode>\n"
					+ "</xmlresponse>";
			responseBody.write(temp.getBytes());
			responseBody.close();
			exchange.close();
			System.out.println("close update page rating handler");

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			exchange.close();
			System.out.println("close update page rating handler");
		}
	}

}
